import { getEditor } from '@inbiz/utils';
import { Modal, message } from 'antd';
import { Toast, Dialog } from 'antd-mobile';
import React from 'react';
import { getMessage } from '@inbiz/react';
import { getvars } from './commonUtils';

// web端service
import {
  submitTask,
  saveDraft,
  sendBack,
  startProcess,
  approval,
  sendTo,
  doItFast,
  removeData,
  cancelProcess,
  withDrawProcess,
  plusSign,
  deleteSended,
} from './web/service';

// web按钮点击
const handleSaveDraft = (param) => {
  const {
    res,
    startResp,
    item,
    inbiz,
    operationSuccess,
    userInfo,
    id,
    formId,
    drafID,
    pageId,
    processId,
    afterSubmit,
  } = param;
  const params = {};
  params.starter = userInfo?.ID;
  params.processDefinitionId = processId;
  params.businessKey = id ? id : res;
  params.formId = formId;
  params.drafID = drafID;
  params.pageId = pageId; // 会返回给我
  saveDraft(params).then((resp) => {
    if (!afterSubmit) {
      operationSuccess(resp, getMessage('global.save'), item);
    } else {
      if (resp.code == '200') {
        const _errorMessage = startResp?.message ? startResp?.message?.replaceAll("'", '') + '，' : '';
        message.error(_errorMessage + getMessage('processButton.saveToDraft'));
        setTimeout(() => {
          window.close();
        }, 500);
      } else {
        const { Name } = inbiz.getModel();
        removeData({
          relations: {
            name: Name,
            children: null,
          },
          data: {
            [Name]: [
              {
                id: id ? id : res,
                _opt: 'del',
              },
            ],
          },
        });
        message.error(resp.message);
      }
    }
  });
};

// 发起流程
const startDraft = (startparam) => {
  const {
    item,
    inbiz,
    operationSuccess,
    userInfo,
    mySummary,
    processvars,
    processId,
    id,
    formId,
    drafID,
    pageId,
  } = startparam;
  const saveDraftParam = {
    item,
    inbiz,
    operationSuccess,
    userInfo,
    id,
    formId,
    drafID,
    pageId,
    processId,
    afterSubmit: true,
  };
  const summary = mySummary?.current || '';
  inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
    if (!res) {
      message.error(getMessage('processButton.modelNotNull'));
      return;
    }
    if (res) {
      const paramsValue = getvars(pageValue, inbiz, 'web', processvars);
      const params = {
        processDefinitionId: `${processId}`,
        starter: `${userInfo?.ID}`,
        summary,
        signDataStr: '',
        businessKey: id ? id : res,
        variablesParams: '',
      };

      params.variablesParams = JSON.stringify(paramsValue);
      startProcess(params)
        .then((resp) => {
          if (resp) {
            if (resp.code !== '200') {
              handleSaveDraft({ ...saveDraftParam, res, startResp: resp });
            } else {
              operationSuccess(resp, getMessage('processButton.initiate'), item);
            }
          }
        })
        .catch(() => {
          message.error(getMessage('processcenter.timeout'));
        });
    }
  });
};
export const handleClick = (commonParam) => {
  const {
    item,
    events,
    inbiz,
    operationSuccess,
    selected,
    mySummary,
    taskId,
    opinions,
    props,
    instanceId,
    taskState,
    processvars,
    processId,
    userInfo,
    id,
    formId,
    drafID,
    pageId,
    $terminateVisible,
    $withDrawVisible,
  } = commonParam;
  const startParam = {
    item,
    inbiz,
    operationSuccess,
    userInfo,
    mySummary,
    processvars,
    processId,
    id,
    formId,
    drafID,
    pageId,
  };
  const saveDraftParam = {
    item,
    inbiz,
    operationSuccess,
    userInfo,
    id,
    formId,
    drafID,
    pageId,
    processId,
  };
  const result = events?.current.onBeforeSubmit?.(item.action) ?? true;
  if (!result || getEditor() || !inbiz.queryData.processId) {
    return false;
  }
  if (item.action == 'initiate') {
    Modal.confirm({
      content: getMessage('processButton.confirminitiate'),
      onOk: () => startDraft(startParam),
      okText: getMessage('global.sure'),
      cancelText: getMessage('global.cancel'),
    });
  } else if (item.action == 'draft') {
    Modal.confirm({
      content: getMessage('processButton.confirmToDraft'),
      okText: getMessage('global.sure'),
      cancelText: getMessage('global.cancel'),
      onOk: () => {
        inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
          if (res) {
            handleSaveDraft({ ...saveDraftParam, res });
          }
        });
      },
    });
  }
  let selectedPeople: any[] = [];
  if (selected.length > 0) {
    selectedPeople = selected.map((item) => ({
      identityId: item.id ?? item.Id,
      guid: item.id ?? item.Id,
      userEmail: item.useremail ?? item.UserEmail,
      id: item.identityid ?? item.IdentityId,
      text: `${item.Name || item.name || ''}(${item.UserLoginName || item.userloginname || ''})`,
      memberType: '0',
      account: item.userloginname ?? item.UserLoginName,
    }));
  }
  const params: any = {};
  const summary = mySummary?.current || '';
  props.emit('onClick', item.action, item);

  switch (item.action) {
    case 'approve':
    case 'refuse':
      params.taskId = taskId;
      params.comment = opinions;
      params.signDataStr = ``;
      params.summary = summary;
      params.isrefuse = item.action == 'refuse';

      const sendparams: any = {};
      sendparams.taskId = taskId;
      sendparams.processInstanceId = instanceId;
      sendparams.jsonStr = JSON.stringify(selectedPeople);
      sendparams.memberType = 0;
      Modal.confirm({
        content:
          item.action == 'refuse'
            ? getMessage('processButton.confirmToRefuse')
            : getMessage('processButton.confirmToPass'),
        onOk: () => {
          inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
            if (res) {
              const paramsValue = getvars(pageValue, inbiz, 'web', processvars);
              params.variablesParams = JSON.stringify(paramsValue);
              if (taskState != 130 && (!inbiz?.workFlow?.ccMember && !inbiz?.workFlow?.baseInfo?.ccMember) && selectedPeople.length > 0) {
                sendTo(sendparams).then((res) => {
                  if (res?.code == '200') {
                    approval(params).then((res1) => {
                      operationSuccess(
                        res1,
                        item.action == 'refuse'
                          ? getMessage('processButton.refuse')
                          : getMessage('processButton.approval'),
                        item,
                      );
                      if (res1?.code != '200') {
                        deleteSended({ processInstanceId: instanceId, taskId })
                      }
                    });
                  } else {
                    message.error(res?.message);
                  }
                })
              } else {
                approval(params).then((res) => {
                  operationSuccess(
                    res,
                    item.action == 'refuse'
                      ? getMessage('processButton.refuse')
                      : getMessage('processButton.approval'),
                    item,
                  );
                });
              }
            }
          });
        },
        okText: getMessage('global.sure'),
        cancelText: getMessage('global.cancel'),
      });
      break;
    case 'cancel':
      $terminateVisible(true);
      break;
    case 'withDraw':
      $withDrawVisible(true);
      break;
    case 'submit':
      Modal.confirm({
        content: getMessage('processButton.confirmToSubmit'),
        onOk: () => {
          inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
            if (res) {
              const paramsValue = getvars(pageValue, inbiz, 'web', processvars);

              paramsValue.push({ name: 'businessKey', value: id ? id : res });

              params.taskId = taskId;
              params.comment = opinions;
              params.signDataStr = ``;
              params.summary = summary;

              params.variablesParams = JSON.stringify(paramsValue);
              submitTask(params).then((response) => {
                operationSuccess(response, getMessage('processButton.submit'), item);
              });
            }
          });
        },
        okText: getMessage('global.sure'),
        cancelText: getMessage('global.cancel'),
      });
      break;
    case 'returnsBack':
    case 'returnsStarter':
    case 'returnsStartModify':
      params.taskId = taskId;
      params.comment = opinions;
      params.signDataStr = ``;
      params.summary = summary;
      let content = '';
      //(previousStep:上一步；sponsor:退回发起人；initiatorModif：退回发起人修改
      if (item.action == 'returnsBack') {
        params.retrunType = 'previousStep';
        content = getMessage('processButton.confirmToReturn');
      } else if (item.action == 'returnsStarter') {
        params.retrunType = 'sponsor';
        content = getMessage('processButton.confirmToStarter');
      } else {
        params.retrunType = 'initiatorModif';
        content = getMessage('processButton.confirmToModifier');
      }

      Modal.confirm({
        content,
        onOk: () => {
          inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
            if (res) {
              sendBack(params).then((response) => {
                operationSuccess(response, getMessage('processButton.returnsBack'), item);
              });
            }
          });
        },
        okText: getMessage('global.sure'),
        cancelText: getMessage('global.cancel'),
      });
      break;
    case 'isUrge':
      params.processDefinitionId = processId;
      params.processInstanceId = instanceId;
      Modal.confirm({
        content: getMessage('processButton.confirmToUrge'),
        onOk: () => {
          inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
            if (res) {
              doItFast(params).then((res) => {
                operationSuccess(res, getMessage('processButton.isUrge'), item);
              });
            }
          });
        },
        okText: getMessage('global.sure'),
        cancelText: getMessage('global.cancel'),
      });
      break;
    case 'print':
      window.print();
      break;
    case 'custom':
      break;
    default:
      break;
  }
};

// 撤回
export const confirmWithDraw = (param) => {
  const { instanceId, inbiz, operationSuccess, instanceNumber } = param;
  if (!instanceNumber) {
    return message.info(getMessage('processButton.inputInstance'));
  } else if (instanceNumber !== instanceId) {
    return message.error(getMessage('processButton.wrongInstance'));
  }
  const params = {
    processInstanceId: instanceNumber,
  };
  inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
    if (res) {
      withDrawProcess(params).then((res) => {
        operationSuccess(res, getMessage('processButton.withDraw'), 'withDraw');
      });
    }
  });
};

// 终止
export const confirmTerminate = (param: any) => {
  const { instanceId, inbiz, operationSuccess, instanceNumber, taskId, $visible, opinions, mySummary } = param;
  if (!instanceNumber) {
    return message.info(getMessage('processButton.inputInstance'));
  } else if (instanceNumber !== instanceId) {
    return message.error(getMessage('processButton.wrongInstance'));
  }
  const params = {
    taskId,
    comment: opinions || '',
    signDataStr: ``,
    processInstanceId: instanceNumber,
    summary: mySummary?.current || '',
  };
  inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
    if (res) {
      cancelProcess(params).then((res) => {
        operationSuccess(res, getMessage('processButton.termination'), 'cancel');
        $visible(false);
      });
    }
  });
};

// 加签

export const countersign = (param: any) => {
  const {
    members,
    value,
    inbiz,
    taskId,
    operationSuccess,
    resetFields,
    $visible,
    $members,
    opinions,
    mySummary,
  } = param;
  if (members.length == 0) {
    return message.info(getMessage('processButton.chooseplusSignPeople'));
  }
  const params = {
    taskId,
    plusSignType: value?.plusSignType ?? inbiz?.workFlow?.buttonSetting?.plusSignLogic ?? inbiz?.workFlow?.plusSignLogic,
    comment: opinions,
    issequential: false,
    assigenLists: members.map((item) => item.id).join(','),
    signDataStr: ``,
    summary: mySummary?.current || '',
  };
  inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
    if (res) {
      plusSign(params).then((res) => {
        operationSuccess(
          res,
          params.plusSignType == 'skipCurrent'
            ? getMessage('processButton.fowardPlusSign')
            : getMessage('processButton.backwardPlusSign'),
          params.plusSignType == 'skipCurrent' ? 'fowardPlusSign' : 'backwardPlusSign',
        );
        resetFields();
        $visible(false);
        $members([]);
      });
    }
  });
};

// wap按钮点击

// 发起
const wapstartDraft = (param) => {
  const {
    inbiz,
    mySummary,
    processvars,
    processId,
    userInfo,
    id,
    operationSuccess,
    item,
    formId,
    drafID,
    pageId,
  } = param;
  const summary = mySummary?.current || '';
  const saveDraftParam = {
    item,
    inbiz,
    operationSuccess,
    userInfo,
    id,
    formId,
    drafID,
    pageId,
    processId,
    afterSubmit: true,
  };
  inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
    if (!res) {
      Toast.show({
        icon: 'fail',
        content: getMessage('processButton.modelnotnull'),
      });
      return;
    }
    if (res) {
      const paramsValue = getvars(pageValue, inbiz, 'wap', processvars);
      const params = {
        processDefinitionId: `${processId}`,
        starter: `${userInfo?.ID}`,
        summary,
        signDataStr: '',
        businessKey: id ? id : res,
        variablesParams: '',
      };

      params.variablesParams = JSON.stringify(paramsValue);
      startProcess(params)
        .then((resp) => {
          if (resp) {
            if (resp.code !== '200') {
              handleSaveDraft({ ...saveDraftParam, res });
            } else {
              operationSuccess(resp, getMessage('processButton.initiate'), item);
            }
          }
        })
        .catch(() => {
          Toast.show({
            icon: 'fail',
            content: getMessage('processButton.timeout'),
          });
        });
    }
  });
};

// 按钮点击
export const waphandleClick = (param) => {
  const {
    item,
    events,
    inbiz,
    userInfo,
    processId,
    id,
    formId,
    drafID,
    pageId,
    operationSuccess,
    $clickedButton,
    $visible,
    mySummary,
    processvars,
  } = param;

  const startParam = {
    inbiz,
    mySummary,
    processvars,
    processId,
    userInfo,
    id,
    operationSuccess,
    item,
    formId,
    drafID,
    pageId,
  };
  const saveDraftParam = {
    item,
    inbiz,
    operationSuccess,
    userInfo,
    id,
    formId,
    drafID,
    pageId,
    processId,
  };
  const result = events.current.onBeforeSubmit?.(item.action) ?? true;
  if (!result || getEditor() || !inbiz.queryData.processId) {
    return false;
  }
  if (item.action == 'initiate') {
    Dialog.confirm({
      content: getMessage('processButton.confirminitiate'),
      closeOnMaskClick: true,
      onConfirm: () => wapstartDraft(startParam),
      confirmText: React.createElement(
        'span',
        { style: { color: 'var(--inbiz-color-primary)' } },
        getMessage('global.sure'),
      ),
      cancelText: React.createElement('span', {}, getMessage('global.cancel')),
    });
  } else if (item.action == 'draft') {
    Dialog.confirm({
      content: getMessage('processButton.confirmToDraft'),
      closeOnMaskClick: true,
      confirmText: React.createElement(
        'span',
        { style: { color: 'var(--inbiz-color-primary)' } },
        getMessage('global.sure'),
      ),
      cancelText: React.createElement('span', {}, getMessage('global.cancel')),
      onConfirm: () => {
        window.timer = setTimeout(() => {
          inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
            handleSaveDraft({ ...saveDraftParam, res });
          });
          clearTimeout(window.timer);
        }, 0);
      },
    });
  } else {
    if (item.action == 'custom') {
    } else {
      $clickedButton(item);
      $visible(true);
    }
  }
};

// 点击更多
export const moreClick = (param) => {
  const { $clickedButton, $visible } = param;
  if (getEditor()) {
    return Toast.show({
      content: getMessage('processButton.previewOperation'),
    });
  }
  $clickedButton({
    action: 'more',
    name: 'processButton.approvalOperation',
    type: '',
    styleType: '',
    bgColor: '',
    fontColor: '',
    taskType: '',
  });
  $visible(true);
};

// 点击确认
export const confirmed = (param) => {
  const {
    inbiz,
    events,
    clickedButton,
    selected,
    mySummary,
    taskId,
    opinions,
    instanceId,
    processvars,
    taskState,
    operationSuccess,
    processInstance,
    processId,
    id,
  } = param;
  if (getEditor() || !inbiz.queryData.tabKey) {
    return;
  }
  const result = events.current.onBeforeSubmit?.(clickedButton.action) ?? true;
  if (!result) {
    return false;
  }
  let selectedPeople: any[] = [];
  if (selected.length > 0) {
    selectedPeople = selected.map((item) => ({
      identityId: item.id ?? item.Id,
      guid: item.id ?? item.Id,
      userEmail: item.useremail ?? item.UserEmail,
      id: item.identityid ?? item.IdentityId,
      text: `${item.Name || item.name || ''}(${item.UserLoginName || item.userloginname || ''})`,
      memberType: '0',
      account: item.userloginname ?? item.UserLoginName,
    }));
  }
  const summary = mySummary?.current || '';
  const params: any = {};
  switch (clickedButton.action) {
    case 'approve':
    case 'refuse': // 这两种action用新接口
      params.taskId = taskId;
      params.comment = opinions;
      params.signDataStr = ``;
      params.summary = summary;
      params.isrefuse = clickedButton.action == 'refuse';

      const sendparams2: any = {};
      sendparams2.taskId = taskId;
      sendparams2.processInstanceId = instanceId;
      sendparams2.jsonStr = JSON.stringify(selectedPeople);
      sendparams2.memberType = 0;

      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          const paramsValue = getvars(pageValue, inbiz, 'wap', processvars);

          params.variablesParams = JSON.stringify(paramsValue);
          if (taskState != 130 && !inbiz?.workFlow.ccMember && !inbiz?.workFlow?.baseInfo?.ccMember) {
            sendTo(sendparams2).then((r) => {
              if (r.code == '200') {
                approval(params).then((res) => {
                  operationSuccess(
                    res,
                    clickedButton.action == 'refuse'
                      ? getMessage('processButton.refuse')
                      : getMessage('processButton.approval'),
                    clickedButton,
                  );
                });
              }
            });
          } else {
            approval(params).then((res) => {
              operationSuccess(
                res,
                clickedButton.action == 'refuse'
                  ? getMessage('processButton.refuse')
                  : getMessage('processButton.approval'),
                clickedButton,
              );
            });
          }
        }
      });
      break;
    case 'withDraw':
      if (!processInstance) {
        return Toast.show({
          icon: 'fail',
          content: getMessage('processButton.inputInstance'),
        });
      } else if (processInstance != instanceId) {
        return Toast.show({
          icon: 'fail',
          content: getMessage('processButton.wrongInstance'),
        });
      }
      params.processInstanceId = processInstance;
      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          withDrawProcess(params).then((res) => {
            operationSuccess(res, getMessage('processButton.withDraw'), clickedButton);
          });
        }
      });
      break;
    case 'submit':
      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          const paramsValue = getvars(pageValue, inbiz, 'wap', processvars);
          if (!id) {
            paramsValue.push({ name: 'businessKey', value: res });
          }
          params.taskId = taskId;
          params.comment = opinions;
          params.signDataStr = ``;
          params.summary = summary;

          params.variablesParams = JSON.stringify(paramsValue);
          submitTask(params).then((response) => {
            operationSuccess(response, getMessage('processButton.submit'), clickedButton);
          });
        }
      });
      break;
    case 'returnsBack':
      params.taskId = taskId;
      params.comment = opinions;
      params.signDataStr = ``;
      params.summary = summary;
      params.retrunType = 'previousStep';
      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          sendBack(params).then((response) => {
            operationSuccess(response, getMessage('processButton.returnsBack'), clickedButton);
          });
        }
      });
      break;
    case 'returnsStarter':
      params.taskId = taskId;
      params.comment = opinions;
      params.signDataStr = ``;
      params.summary = summary;
      params.retrunType = 'sponsor';
      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          sendBack(params).then((response) => {
            operationSuccess(response, getMessage('processButton.returnsBack'), clickedButton);
          });
        }
      });
      break;
    case 'returnsStartModify':
      params.taskId = taskId;
      params.comment = opinions;
      params.signDataStr = ``;
      params.summary = summary;
      params.retrunType = 'initiatorModif';
      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          sendBack(params).then((response) => {
            operationSuccess(response, getMessage('processButton.returnsBack'), clickedButton);
          });
        }
      });
      break;
    case 'cancel':
      if (!processInstance) {
        return Toast.show({
          icon: 'fail',
          content: getMessage('processButton.inputInstance'),
        });
      } else if (processInstance != instanceId) {
        return Toast.show({
          icon: 'fail',
          content: getMessage('processButton.wrongInstance'),
        });
      }
      params.taskId = taskId;
      params.comment = opinions;
      params.signDataStr = '';
      params.processInstanceId = processInstance;
      params.summary = summary;

      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          cancelProcess(params).then((res) => {
            operationSuccess(res, getMessage('processButton.termination'), clickedButton);
          });
        }
      });
      break;
    case 'fowardPlusSign':
      if (selected.length == 0) {
        return Toast.show({ content: getMessage('processButton.chooseplusSignPeople') });
      }
      params.taskId = taskId;
      params.plusSignType = 'skipCurrent';
      params.comment = opinions;
      params.issequential = false;
      params.assigenLists = selected.map((item) => item.id).join(',');
      params.summary = summary;
      params.signDataStr = '';
      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          plusSign(params).then((res) => {
            operationSuccess(res, getMessage('processButton.fowardPlusSign'), clickedButton);
          });
        }
      });
      break;
    case 'backwardPlusSign':
      if (selected.length == 0) {
        return Toast.show({ content: getMessage('processButton.chooseplusSignPeople') });
      }
      params.taskId = taskId;
      params.plusSignType = 'skipNext';
      params.comment = opinions;
      params.issequential = false;
      params.assigenLists = selected.map((item) => item.id).join(',');
      params.summary = summary;
      params.signDataStr = '';
      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          plusSign(params).then((res) => {
            operationSuccess(res, getMessage('processButton.backwardPlusSign'), clickedButton);
          });
        }
      });
      break;
    case 'isUrge':
      params.processDefinitionId = processId;
      params.processInstanceId = instanceId;
      inbiz?.submit?.(true).then(({ id: res, pageValue }) => {
        if (res) {
          doItFast(params).then((res) => {
            operationSuccess(res, getMessage('processButton.isUrge'), clickedButton);
          });
        }
      });
      break;
    case 'print':
      window.print();
      break;
    case 'custom':
      break;
    default:
      break;
  }
};
